#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

char devname[] = "/proc/buffer1k";

char read_buf[1025];
void read_proc(int fd)
{
    int ret;

    while (1) {
        ret = read(fd, read_buf, sizeof(read_buf) - 1);
        if (ret > 0) {
            printf("读%s, data=%s\n", devname, read_buf);
        }
        else if (ret == 0) {
            printf("end 读proc文件结束, %s\n", devname);
            break;
        }
        else {
            printf("error 读proc文件 失败, %s\n", devname);
            break;
        }
    }
}

void init_buf(char buf[], unsigned int len)
{
    // 初始化为可视化字符 !~/,0~9,A~Z,a~z
    int rang = 'z' - '0';
    int i;
    for (i = 0;i < len;i++) {
        buf[i] = i % rang + '0';
    }
}

void write_proc(int fd)
{
    int ret;
    char data[65] = { 0 };
    init_buf(data, sizeof(data) - 1);
    while (1) {
        ret = write(fd, data, sizeof(data) - 1);
        if (ret > 0) {
            printf("写%s, data=%s\n", devname, data);
        }
        else if (ret == 0) {
            printf("end 写proc文件结束, %s\n", devname);
            break;
        }
        else {
            printf("error 写proc文件 失败, %s\n", devname);
            break;
        }
    }
}

int main(int argc, char* argv[])
{

    int fd;
    fd = open(devname, O_RDWR);
    if (fd <= 0) {
        perror("open dev failed");
        return 1;
    }
    write_proc(fd);
    close(fd);

    printf("--------------------------------\n");
    // lseek(fd,SEEK_SET,0);    // proc 文件不支持lseek
    fd = open(devname, O_RDWR);
    read_proc(fd);
    close(fd);


    return 0;
}